<?php
namespace App\Lib\Auth;

use App\UserGroup;

trait CurrentUserGroupTrait
{
    private $managedGroups = null;

    public function getCurrentUserGroup($groupId)
    {
        $group = UserGroup::findOrFail($groupId);

        if ($group->isExternalEnterprise() || $group->isSimpleUserGroup()) {
            return $group;
        } else if ($group->isInternalOrganization() || $group->isInternalDepartment()) {
            return $group->coreOrganization();
        }

        return null;
    }

    public function getRootInternalOrganization()
    {
        return UserGroup::whereNull('parent_id')
            ->where('group_type', UserGroup::$GROUP_TYPE_INTERNAL_ORGANIZATION)
            ->where('active_status', UserGroup::$GROUP_STATUS_ACTIVE)
            ->first();
    }

    public function getAllManagedGroups($groupId, $hasSelf=true)
    {
        $this->managedGroups = [];

        if ($hasSelf) {
            array_push($this->managedGroups, UserGroup::findOrFail($groupId));
        }

        $this->getChildGroups($groupId);

        return $this->managedGroups;
    }

    private function getChildGroups($groupId)
    {
        $childGroups = UserGroup::where('parent_id', $groupId)
            ->where('active_status', UserGroup::$GROUP_STATUS_ACTIVE)
            ->get();

        foreach ($childGroups as $childGroup) {
            array_push($this->managedGroups, $childGroup);
            $this->getChildGroups($childGroup->id);
        }
    }
}
